package com.bw.interceptor;

import com.bw.domain.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//登录拦截器
public class LoginIntecetor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1如果用户已登录。则不拦截
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");//从session获取登录的对象
        if(null!=user){
            return true;//有值则说明等。则放行
        }

        //2 如果没有登录则把用户的请求转发到登录页面
        request.setAttribute("loginMsg","请求失败，检查是否有权限或是否登录");
        request.setAttribute("user",new User());//登录页面使用的form标签，需要user对象

       request.getRequestDispatcher("/WEB-INF/view/login.jsp").forward(request,response);

        return false;//拦截
    }
}
